mini.parse();
var projectName = $("#projectName").val();
var form0 = new mini.Form("form0");
var form1 = new mini.Form("form1");
var form2 = new mini.Form("form2");
var id= mini.get("id").getValue();
var taskId= mini.get("taskId").getValue();
var dymcformId= mini.get("dymcformId").getValue();
var tableName= mini.get("tableName").getValue();
autoGridLoad();//子表控件加载数据
setFormData();

function isExitsFunction(functionName){
	var result = true;
	try{
		if(eval(functionName+"()")){ //functionName 方法执行结果为true
			result = true;
		}else{ //functionName 方法执行结果为false;
			result = false;	
		}
	}catch(e){ // 没有定义functionName方法
		console.log(e);
		result = true;
	}
	return result;
}
/**保存*/
function onClick(e) {
	mini.mask({
        el: document.body,
        cls: 'mini-mask-loading',
        html: '正在保存信息...'
    });
	if(isExitsFunction("beforeSave")){
		 SaveFormData();
	}
	 mini.unmask();
 }
/**发送**/
function onSend(e){
	mini.mask({
        el: document.body,
        cls: 'mini-mask-loading',
        html: '正在保存信息...'
    }); 
	// 先验证
	if(isExitsFunction("beforeSend")){
		SaveFormData(callFlowInfc);
	}
    mini.unmask();
}

function CloseWindow(action) {
    if (window.CloseOwnerWindow) return window.CloseOwnerWindow(action);
    else window.close();
}

function SaveFormData(callback) {
	if(callback && typeof(callback)=="function"){
		form2.validate();
		if (form2.isValid() == false) return;
	}
	var json1 = mini.encode(getSubtableData(GetFormData(form2)));
	json1 = copyListForInstall(json1);//这一步操作是安装单为适配小程序端，将设备详情列表同步到安装列表
	mini.get("htmlValue").setValue(json1);
	var json = mini.encode(GetFormData(form1));
	mini.mask({
        el: document.body,
        cls: 'mini-mask-loading',
        html: '正在保存信息...'
    }); 
	$.ajax({
		url : projectName+"/DymcformDisplayAdmin/saveFormData",
		type : 'post',
		contentType : "application/json; charset=utf-8",
		dataType : 'json',
		data : json,
		cache : false,
		success : function(data) {
			mini.unmask();
			if (data.status == '1') {
				id = data.result.id;
				mini.get("id").setValue(data.result.id);
				if(data.result.version){
					mini.get("version").setValue(data.result.version);
				}
				reGridLoad();
				if(callback && (typeof(callback) == "function")){
					callback();
				}else{
					mini.alert(data.message, "" , function() {
						
					});
				}
			} else if(data.status == '0') {
				mini.alert(data.message);
			} else {
				mini.alert("发生错误!");
			}
		},
		error : function(jqXHR, textStatus, errorThrown) {
			mini.alert(jqXHR.responseText);
		}
	});
}

function GetFormData(form_Name){
	var o = form_Name.getData();
	return o;
}
function setFormData(){
	if(id==""){return }
	mini.mask({
        el: document.body,
        cls: 'mini-mask-loading',
        html: '正在加载信息...'
    }); 
	$.ajax({
		url : projectName+"/DymcformDisplayAdmin/getFormData?pkvalue="+id+"&dymcformId="+dymcformId+"&tableName="+tableName,
		type : 'get',
		dataType : 'json',
		cache : false,
		success : function(data) {
			mini.unmask();
			if (data.status == '1') {
				reGridLoad();
				var data11 = mini.decode(data.result.result);
				form2.setData(data11);
			} else if(data.status == '0') {
				mini.alert(data.message);
			} else {
				mini.alert("发生错误!");
			}
		},
		error : function(jqXHR, textStatus, errorThrown) {
		    mini.unmask();
			mini.alert(jqXHR.responseText);
		}
	});
}
/**获取子表的数据**/
function getSubtableData(o){
	var subtableList = [];//
	$.each($(".subtable"),function(){
		var name = $(this).attr("name");
		var grid = mini.get(name+"_datagrid");
		try{
			var obj = eval("grid.getChanges()");
			o[name] = obj;
		}catch(e){
			console.log(e);
		}
	});
	return o;
}
/**子表初始化加载*/
function autoGridLoad(){
	$.each($(".subtable"),function(){
		var name = $(this).attr("name");
		var grid = mini.get(name+"_datagrid");
		try{
			grid.load();
		}catch(e){
			console.log("子表"+name+"数据加载失败");
		}
		
	});
}
/**重新加载子表表格**/
function reGridLoad(){
	$.each($(".subtable"),function(){
		var name = $(this).attr("name");
		var grid = mini.get(name+"_datagrid");
		var url = projectName+"/DymcformDisplayAdmin/getSubTableData?tableName="+tableName+"_zb_"+name+"&mainTableId="+id;
		try{
			grid.setUrl(url)
			grid.load();
		}catch(e){
			console.log("加载失败的表格"+name);
		}
	});
}
/**调用流程变量**/
function callFlowInfc(){
	var json = mini.encode(GetFormData(form0));
	mini.mask({
        el: document.body,
        cls: 'mini-mask-loading',
        html: '正在发送信息...'
    }); 
	$.ajax({
		url : projectName+'/ActivitiTaskAdmin/completeTask',
		type : 'post',
		contentType : "application/json; charset=utf-8",
		dataType : 'json',
		data : json,
		cache : false,
		success : function(data) {
			mini.unmask();
			if (data.status == '1') {
				mini.alert(data.message, "" , function() {
					CloseWindow("");
				});
			} else if(data.status == '0') {
				mini.alert(data.message);
			} else {
				mini.alert("发生错误!");
			}
		},
		error : function(jqXHR, textStatus, errorThrown) {
		    mini.unmask();
			mini.alert(jqXHR.responseText);
		}
	});
}

//安装单  同步确认设备列表
function sync_install(myflag,obj){
	if(myflag == 'copyTo'){
		var listGrid = mini.get("equipment_list_datagrid");
		var listData = listGrid.getData();
		var arr=[];
		for (var i = 0; i < listData.length; i++) {
			var row = listGrid.getRow(i);
			var jsonData = {EQ_TYPE_NAME: row.EQ_TYPE_NAME,
				            EQ_NAME: row.EQ_NAME,
				            ORG_ID: row.ORG_ID,
				            CONTRACT_NO: row.CONTRACT_NO,
				            EQ_CODE: row.EQ_CODE,
				            SUPPLIER_ID: row.SUPPLIER_ID,
				            SUPPLIER_NAME: row.SUPPLIER_NAME,
				            EQ_TYPE_ID: row.EQ_TYPE_ID,
				            EQ_ID: row.EQ_ID,
				            EQ_NUM: row.EQ_NUM,
				            _id: row._id,
				            _uid: row._uid,
				            _state: 'added'}
			arr.push(jsonData);
		}
		var stringData = mini.encode(arr);
		obj.equipment_detail = mini.decode (stringData, false);
	}
	var listObj = obj.equipment_list;
	for (var i = 0; i < listObj.length; i++) {
		var o =obj.equipment_list[i];
		if(o._state == 'modified'&&(!o.id)){
			o._state = 'added';
		}
	}
}

//维修单  同步出库  确认设备列表
function sync_service(obj,tableName){
	var data1 = grid1.getData();
	var arr=[];
	for (var i = 0; i < data1.length; i++) {
		var row = grid1.getRow(i);
		var jsonData = {
			ID : row.ID,
			EQ_TYPE_ID : row.EQ_TYPE_ID,
			EQ_TYPE_NAME : row.EQ_TYPE_NAME,
			EQ_NUM : row.EQ_NUM,
			_id : row._id,
			_uid : row._uid,
			_state : 'added'
		}
		arr.push(jsonData);
	}
	var stringData = mini.encode(arr);
	obj[tableName] = mini.decode (stringData, false);
}

function copyListForInstall(json1){
	var myflag = mini.get("htmlValue").getValue();
	var obj = mini.decode (json1, false);
	if(myflag && (myflag == 'copyTo' || myflag == 'modifiedFlag')){
		sync_install(myflag,obj);
	}
	if(myflag && myflag == 'syncGrid2_service'){ 
		sync_service(obj,'new_equipment_list');
	}
	if(myflag && myflag == 'syncGrid3_service'){ 
		sync_service(obj,'confirm_equipment_list');
	}
	json1 = mini.encode (obj);
	return json1;
}

 

